from typing import Optional, List

from fastapi import APIRouter, Query, Body

from server.app.cloud_ide.schema.roles.request.role_create_request import RoleCreateRequest
from server.app.cloud_ide.schema.roles.request.role_update_request import RoleUpdateRequest
from server.app.cloud_ide.schema.roles.response.role_info_response import RoleInfoResponse
from server.app.cloud_ide.service.role_service import RoleService
from server.framework.core.http_schemas import CommonResponseSchema, TableResponseSchema
from server.framework.core.schemas import OptionsSchema

role_api = APIRouter()
role_service = RoleService()


@role_api.get("/list", response_model=TableResponseSchema, name='获取角色列表')
async def list(tenant_id: str = Query(None, description='租户id'),
               current: Optional[int] = Query(1, description='当前页数'),
               page_size: Optional[int] = Query(10, description='每页记录的数量', alias='pageSize')) -> TableResponseSchema:
    results = role_service.get_role_list(tenant_id)
    return TableResponseSchema(data=results[current - 1:current * page_size], total=len(results), page=page_size,
                               success=True)


@role_api.get("/get_role_options", name='获取角色的下拉选项')
async def get_ide_environment_options(tenant_id: str = Query(None, description='租户id')) -> List[OptionsSchema]:
    roles = role_service.get_role_list(tenant_id)
    option_results: List[OptionsSchema] = []
    for role in roles:
        option_results.append(OptionsSchema(value=role.id, label=role.name))
    return option_results


@role_api.post("/create", response_model=CommonResponseSchema, name='创建角色')
async def create(data: RoleCreateRequest = Body(None, description='角色创建实体')) -> CommonResponseSchema:
    result = role_service.create_role(data)
    if result:
        return CommonResponseSchema(data={}, message=f'创建成功', success=True)
    else:
        return CommonResponseSchema(data={}, message=f'创建失败', success=False)


@role_api.get("/get_entity", name='获取角色实体')
async def get_entity(id: str = Query(None, description='角色id')) -> RoleInfoResponse:
    entity = role_service.get_role_entity(id)
    return entity


@role_api.post("/edit", response_model=CommonResponseSchema, name='更新角色')
async def edit(data: RoleUpdateRequest = Body(None, description='角色更新实体')) -> CommonResponseSchema:
    rs = role_service.update_role(data)
    if rs:
        return CommonResponseSchema(data={}, message=f'更新成功', success=True)
    else:
        return CommonResponseSchema(data={}, message=f'更新失败', success=False)


@role_api.get("/delete", response_model=CommonResponseSchema, name='删除角色')
async def delete(
        ids: str = Query(None, description='角色id，多条记录以逗号分割')) -> CommonResponseSchema:
    role_ids = ids.split(',')
    rs = role_service.delete_roles(role_ids)
    if rs:
        return CommonResponseSchema(data={}, message=f'删除成功', success=True)
    else:
        return CommonResponseSchema(data={}, message=f'删除失败', success=False)
